// Copyright  2004-2008 Backplane Ltd.
//
// This file is part of Ubiquity formsPlayer
//
// Ubiquity formsPlayer is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
//
// Ubiquity formsPlayer is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License
// along with Ubiquity formsPlayer If not, see <http://www.gnu.org/licenses/>.
//	
//
//   Purpose: implementation of CImplCase.
//   $Id$


#include "stdafx.h"
#include "case.h"
#include "switch.h"
#include "idResolver.h"

CImplCase::CImplCase()
	:m_pSwitch(0)
	,m_bIsActive(false)
{
}

// Bug 265 - Add this constructor which is called on parse of 
// the xf:case element.
CImplCase::CImplCase(CXFormsElementCase * pElement)
	: CFormControl((CXFormsElement*) pElement)
	,m_pSwitch(0)
	,m_bIsActive(false)
{
}

CImplCase::~CImplCase()
{
	//to be safe, we should remove this case from its parent
	//	switch,  Just in case NodesWithId removes it before
	//	it destroys switch.
	//if the other way round, we don't have to worry, as cases
	//	are all destroyed in their switch's destructor, so the switch
	//	will always be alive when the case is destroyed.

	try
	{
		if(m_pSwitch)
			//remove from the switch list.
			m_pSwitch->removeCaseReference(this);
	}
	catch(...){ASSERT(0);}


}

HRESULT CImplCase::select()
{
	m_bIsActive = true;
	return onselect();
}

HRESULT CImplCase::deselect()
{
	m_bIsActive = false;
	return ondeselect();
}

// This is the same as the showFocus() for group
// Need to create base class
// Locates the first xforms child of the case and set focus to it.
HRESULT CImplCase::showFocus()
{
	HRESULT hr = FireEvent(EVENT_FOCUS);
	if(SUCCEEDED(hr))
	{
		hr = S_FALSE;
		POSITION pos = m_Children.GetStartPosition();
		while(pos)
		{
            CImpl * pImpl = NULL;
			m_Children.GetNextAssoc(pos, pImpl, pImpl);
			if(pImpl)
			{
				CFormControl * pControl = dynamic_cast<CFormControl*>(pImpl);
				if(pControl)
				{
					hr = pControl->setFocus();
					break;
				}
			}
		}
	}

	return hr;
}

bool CImplCase::IsActive() const
{
	return m_bIsActive;
}

HRESULT CImplCase::toggle()
{
	HRESULT hr;
	if(m_pSwitch)
	{
		hr = m_pSwitch->toggle(this);
		// To be added after restructure of Case......
		// showFocus();
	}
	else
		hr = E_UNEXPECTED;
	return hr;
};

HRESULT CImplCase::init(CImpl * pParent)
{
	HRESULT hr = S_OK;
	
	hr = CFormControl::init(pParent);

	if(m_sId)
	{
		GetIdResolver()->AddItem(this);
	}
	setModel(0);

	return hr;
}